package com.tianqingwl.gsystem.template.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianqingwl.gsystem.common.enumeration.TemplateConfig;
import com.tianqingwl.gsystem.common.vo.CommonResultVo;
import com.tianqingwl.gsystem.resources.pojo.SysFileResource;
import com.tianqingwl.gsystem.resources.service.SysConfigService;
import com.tianqingwl.gsystem.template.mapper.SysTemplateMapper;
import com.tianqingwl.gsystem.template.pojo.SysTemplate;
import com.tianqingwl.gsystem.template.service.SysTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Service
public class SysTemplateServiceImpl implements SysTemplateService {
    @Autowired
    private SysTemplateMapper sysTemplateMapper;
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public CommonResultVo saveFile(MultipartFile[] files) {
        CommonResultVo result = new CommonResultVo();
        if (files != null && files.length > 0) {
            try {
                List<SysFileResource> fileResourceList = new ArrayList<>();
                String filePath = FileUtil.getAbsolutePath("templateUpload");
                for (MultipartFile file : files) {
                    //取基本信息、文件存储
                    String fileName = file.getOriginalFilename();

                    File uploadPathFile = new File(filePath);
                    if (!uploadPathFile.exists()) {
                        uploadPathFile.mkdirs();
                    }
                    File originalUploadFile = new File(filePath + File.separator + fileName);
                    file.transferTo(originalUploadFile);
                    //解压模板
                    File unzipFile = ZipUtil.unzip(originalUploadFile);
                    //模板校验
                    File templateConfig = new File(unzipFile.getAbsolutePath() + File.separator + "config.properties");
                    if (!templateConfig.exists()) {
                        return CommonResultVo.fail("没有找到配置文件，模板包请按格式制作");
                    }
                    EncodedResource encodedResource = new EncodedResource(new PathResource(templateConfig.getAbsolutePath()), "UTF-8");
                    Properties properties = PropertiesLoaderUtils.loadProperties(encodedResource);
                    //提取文件信息
                    String templateDir = properties.getProperty(TemplateConfig.templateDir);
                    String staticDir = properties.getProperty(TemplateConfig.staticDir);
                    String templateName = properties.getProperty(TemplateConfig.templateName);
                    String author = properties.getProperty(TemplateConfig.author);
                    String authorHomePage = properties.getProperty(TemplateConfig.authorHomePage);
                    String templatePage = properties.getProperty(TemplateConfig.templatePage);
                    String cover = properties.getProperty(TemplateConfig.cover);
                    String desc = properties.getProperty(TemplateConfig.desc);
                    //下面一坨判断有先后顺序
                    if (StrUtil.isEmpty(templateDir)) {
                        return CommonResultVo.fail("没有配置模板路径");
                    }
                    File templateDirFile = new File(unzipFile.getAbsolutePath() + File.separator + templateDir);
                    if (!templateDirFile.exists()) {
                        return CommonResultVo.fail("配置的模板路径不存在");
                    }
                    if (StrUtil.isEmpty(staticDir)) {
                        return CommonResultVo.fail("没有配置静态资源路径");
                    }
                    File staticDirFile = new File(unzipFile.getAbsolutePath() + File.separator + staticDir);
                    if (!staticDirFile.exists()) {
                        return CommonResultVo.fail("配置的静态资源路径不存在");
                    }

                    if (StrUtil.isEmpty(templateName)) {
                        return CommonResultVo.fail("没有配置模板名字");
                    }
                    if (StrUtil.isEmpty(author)) {
                        return CommonResultVo.fail("没有配置作者");
                    }
                    if (StrUtil.isEmpty(authorHomePage)) {
                        return CommonResultVo.fail("没有配置作者主页");
                    }
                    if (StrUtil.isEmpty(templatePage)) {
                        return CommonResultVo.fail("没有配置模板主页");
                    }
                    if (StrUtil.isEmpty(cover)) {
                        return CommonResultVo.fail("没有配置封面图");
                    }
                    File coverFile = new File(unzipFile.getAbsolutePath() + File.separator + staticDir + File.separator + cover);
                    if (!coverFile.exists()) {
                        return CommonResultVo.fail("配置的封面图不存在");
                    }
                    if (StrUtil.isEmpty(desc)) {
                        return CommonResultVo.fail("配置的模板路径不存在");
                    }
                    //检查是否已存在目标文件夹
                    File targetStyleFile = new File(FileUtil.getAbsolutePath("static" + File.separator + staticDir));
                    if (targetStyleFile.exists()) {
                        return CommonResultVo.fail("与现有的已有的静态资源文件夹冲突");
                    }
                    File targetTemplateFile = new File(FileUtil.getAbsolutePath("templates" + File.separator + templateDir));
                    if (targetTemplateFile.exists()) {
                        return CommonResultVo.fail("与现有的已有的模板文件夹冲突");
                    }
                    //移动样式文件、模板文件
                    FileUtil.copy(staticDirFile, new File(FileUtil.getAbsolutePath("static")), false);
                    FileUtil.copy(templateDirFile, new File(FileUtil.getAbsolutePath("templates")), false);
                    //删除原件
                    FileUtil.del(unzipFile);
                    originalUploadFile.delete();
                    //数据持久化
                    SysTemplate sysTemplate = new SysTemplate();
                    sysTemplate.setTemplateDesc(desc);
                    sysTemplate.setTemplateDir(templateDir);
                    sysTemplate.setTemplateName(templateName);
                    sysTemplate.setStaticDir(staticDir);
                    sysTemplate.setAuthor(author);
                    sysTemplate.setAuthorHomePage(authorHomePage);
                    sysTemplate.setTemplatePage(templatePage);
                    sysTemplate.setCover("/" + staticDir + "/" + cover);
                    sysTemplate.setStatus(0);

                    sysTemplateMapper.insert(sysTemplate);
                }
                result = CommonResultVo.success();
            } catch (IOException ioException) {
                result = CommonResultVo.fail(ioException.getMessage());
            }
        } else {
            result = CommonResultVo.fail("template file empty");
        }
        return result;
    }

    @Override
    public void listSysTemplate(Page<SysTemplate> sysTemplatePage) {
        QueryWrapper<SysTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("templateId");
        sysTemplateMapper.selectPage(sysTemplatePage, queryWrapper);
    }

    @Override
    public void delete(Long templateId) {
        //先检查是否是默认模板
        SysTemplate sysTemplate = sysTemplateMapper.selectById(templateId);
        if (sysTemplate==null){
            throw new RuntimeException("not found");
        }
        if ("default".equals(sysTemplate.getTemplateDir())){
            throw new RuntimeException("default template can't delete");
        }
        //仅剩2个时启用默认
        int count = sysTemplateMapper.selectCount(new QueryWrapper<>());
        if (count==2){
            sysTemplateMapper.updateTemplateEnable(1L);
        }
        //删除模板文件夹
        File templateFile = new File(FileUtil.getAbsolutePath("templates" + File.separator + sysTemplate.getTemplateDir()));
        if (templateFile.exists()){
            FileUtil.del(templateFile);
        }
        //删除静态资源文件夹
        File staticFile = new File(FileUtil.getAbsolutePath("static" + File.separator + sysTemplate.getStaticDir()));
        if (staticFile.exists()){
            FileUtil.del(staticFile);
        }
        //删除数据
        sysTemplateMapper.deleteById(templateId);
    }

    @Transactional
    @Override
    public void updateStatus(Long templateId) {
        sysTemplateMapper.updateAllDisabled();
        sysTemplateMapper.updateTemplateEnable(templateId);
        //TODO 考虑使用缓存，防止在并发一瞬间找不到模板
    }

    @Override
    public SysTemplate getCurrentTemplate() {
        //获取数据库启用的模板
        QueryWrapper<SysTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        SysTemplate sysTemplate = sysTemplateMapper.selectOne(queryWrapper);
        return sysTemplate;
    }
}
